import { TaskService } from '@/services/bussiness/Task/task.service'
import { useHomeFormStore } from '@/stores/home/form.store'
import { ElLoading, ElMessage } from 'element-plus'
import { DagChart } from './dag.chart'
const homeFormStore = useHomeFormStore()

export function initClickEvent(dagChart: DagChart) {
  const { chart, dagId } = dagChart
  const canvasDom = chart.getDom()
  let chartEleFlag = false
  chart.on('click', function (event: any) {
    chartEleFlag = true
    if (dagChart.createEdgeInfo.flag) {
      dagChart.addEdgeEnd(event.data.name)
    }
    if (!event.data.source) {
      // 节点
      const taskId = event.data?.taskInfo?.taskId
      homeFormStore.updateCurrentTaskId(taskId)
      showDagLog(dagId, taskId)
    }
  })

  canvasDom.addEventListener('click', (event: any) => {
    if (!chartEleFlag && dagChart.createEdgeInfo.flag) {
      dagChart.addEdgeStop()
    }

    chartEleFlag = false
    event.stopPropagation()
    event.preventDefault()
  })
}

async function showDagLog(dagId: number, taskId: number) {
  const dagExecutionId = homeFormStore.dagExecutionId
  if (dagExecutionId && taskId) {
    const loading = ElLoading.service()
    const response = await TaskService.getDagLog(dagId, dagExecutionId, taskId)
    loading.close()

    if (Array.isArray(response)) {
      homeFormStore.updateDagLog(response)
    } else {
      homeFormStore.updateDagLog(null)
      ElMessage({
        message: response.code + response.msg || '获取日志失败',
        type: 'warning'
      })
    }
  }
}
